package Andrew;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;

public class DiscoveryService {

	/**
	 * The service type to browse for. This should be the same as the one you
	 * use to register services with.
	 */
	public static final String SERVICE_TYPE = "_media_service._tcp.local.";

	/**
	 * This class implements the ServiceListener interface which receives
	 * notifications when services are discovered and lost. Note that in your
	 * implementations the listener will probably form part of another class;
	 * not a static, stand-alone class like this. Think about how you might add
	 * listeners in the Swing framework for example.
	 */
	static class SampleListener implements ServiceListener {
		@Override
		public void serviceAdded(final ServiceEvent event) {
			System.out.println("Service added   : " + event.getName() + "."
					+ event.getType());
			// The following line is required to get all information associated
			// with a service registration - not just the name and type - for
			// example, the port number and properties. Notification is sent to
			// the
			// serviceResolved(...) method which the request has been completed.
			event.getDNS().requestServiceInfo(event.getType(), event.getName(),
					0);
		}

		@Override
		public void serviceRemoved(final ServiceEvent event) {
			System.out.println("Service removed : " + event.getName() + "."
					+ event.getType());
		}

		@Override
		public void serviceResolved(final ServiceEvent event) {
			// Display some information about the service.
			System.out.println("Service resolved: " + event.getInfo().getName()
					+ ", host: " + event.getInfo().getHostAddress()
					+ ", port: " + event.getInfo().getPort());
			System.out.println(event.getInfo().getHostAddress());

			// When the service has been resolved send our message to that
			// service using its address and port number.
			final TestClient client = new TestClient(event.getInfo()
					.getHostAddress(), event.getInfo().getPort());
			client.sendMessage("LIST");
		}
	}

	public static void main(final String[] args) throws IOException {
		// Again, you can specify which network interface you would like to
		// browse
		// for services on; see commented line.
		// final JmDNS jmdns = JmDNS.create(InetAddress.getLocalHost());
		final JmDNS jmdns = JmDNS.create();

		// Work the magic: this is where the service listener is registered.
		jmdns.addServiceListener(DiscoveryService.SERVICE_TYPE,
				new SampleListener());

		System.out.println("Press enter to quit");
		new BufferedReader(new InputStreamReader(System.in)).readLine();
		jmdns.close();
		System.exit(0);
	}
}
